// pages/login/login.js
import tool from '../../modules/tool'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginType: 0,
    form: {
      phone: '',
      password: '',
      account: '',
      vcode: ''
    },
    error: '',
    vcodeText: '发送验证码',
    handleSendVCodeWithDebounce: () => { },
    home: {}
  },

  async handleSendVCodeInsideMethod() {
    console.log(this.data.form)
    if (!tool.check.phone(this.data.form.phone)) {
      tool.handleShowToast('输入手机号', 'error')
      return
    }
    if (this.data.vcodeText != '发送验证码') {

      return
    }
    this.setData({
      vcodeText: `正在发送`
    })
    let re = await tool.requestData('/user/getVCode', {
      phone: this.data.form.phone
    }, 'get')
    if (re.status == 1) {
      tool.postFrontStatus(`点击发送验证码`)
      for (let i = 59; i >= 0; i--) {
        await tool.wait(1)
        this.setData({
          vcodeText: `${i}秒后可重发`
        })
      }
      this.setData({
        vcodeText: `发送验证码`
      })
    } else {
      tool.handleShowToast(re.content, 'error')
    }
  },

  async handleSendVCode() {
    this.data.handleSendVCodeWithDebounce()
  },

  handleClickReg() {
    tool.postFrontStatus(`点击注册`)
    wx.redirectTo({
      url: '/pages/register/register',
    })
  },

  async handleClickLogin() {
    tool.postFrontStatus(`点击登录`)
    tool.flow(async () => {
      if (this.data.loginType == 0) {
        if (!this.data.form.account) throw '输入学号/工号'
        if (!this.data.form.password) throw '输入密码'
      } else {
        if (!tool.check.phone(this.data.form.phone)) throw '输入正确的手机号'
        if (!this.data.form.vcode) throw '输入验证码'
      }
      let re = await tool.requestData('/user/setOpenId', {
        ...this.data,
        code: await tool.getLoginCode()
      })
      if (re.status == 1) {
        tool.handleShowToastWithMask('登录成功')
        await tool.wait(0.5)
        tool.redirectToIndex()
      } else {
        throw re.content
      }
    }, (e) => tool.handleShowToast(e, 'error'))
  },

  handleInput(e) {
    let t = this.data.form
    t[e.currentTarget.dataset.field] = e.detail.value
    this.setData({
      form: t
    })
  },

  handleChangeLoginType(e) {
    e = e.currentTarget.dataset.type
    tool.postFrontStatus(`切换登录方式 ${e}`)
    this.setData({
      loginType: e
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    tool.setPageData(this)
    this.setData({
      handleSendVCodeWithDebounce: tool.debounce(this.handleSendVCodeInsideMethod),
      home: tool.store.getItem('home')
    })
    tool.postFrontStatus(`登录界面`)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})